package com.jmu.bishe.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.jmu.bishe.entity.House;
import com.jmu.bishe.entity.Member;
import com.jmu.bishe.entity.News;
import com.jmu.bishe.service.HouseService;
import com.jmu.bishe.service.NewsService;
import com.jmu.bishe.service.UserService;
import com.jmu.bishe.service.main.TableService;
import com.jmu.bishe.utils.BeanUtils;
import com.jmu.bishe.utils.StringUtils;
import com.jmu.bishe.web.common.BaseController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
public class HouseController extends BaseController{
	@Autowired
	private TableService tableService;
	@Autowired
	private HouseService houseService;
	@Autowired
	private UserService userService;

	/**
	 * 发布房源页面
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/publish-house.do") 
    public String publishnews(Model model,HttpServletRequest request) throws Exception {
		if(!StringUtils.isBlank(request.getParameter("hid"))){
			House house = houseService.getHouse(request.getParameter("hid"));	
			Member m = getCurUser(request);
			if(!house.getUserId().equals(m.getUserId())&&!"0".equals(m.getRole())){
				//是本人发布的或者是超级管理员，才可以修改
				return "redirect:/admin/my-house.do";
			}
			model.addAttribute("house", house);
		}
        return "publish-house";
    }
   
	/**
	 * 发布房源
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/publish-house.do",method=RequestMethod.POST) 
    public String dopublishhouse(Model model,HttpServletRequest request,House house) throws Exception {	
		Member m = getCurUser(request);
		if(StringUtils.isBlank(house.getHid())){
			house.setUserId(m.getUserId());
			house.setDisplay_date(new Date());
			house.setStatus(0);
			houseService.saveOrUpdate(house);
		}else{
			House oldHouse = houseService.getHouse(house.getHid()) ;
			if(oldHouse.getUserId().equals(m.getUserId())||"0".equals(m.getRole())){
				BeanUtils.BeanToBean(house, oldHouse);
				houseService.saveOrUpdate(house);
			}
		}

		return "edit-profile";
    }
	/**
	 * 房源内容
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/house/housecontent.do") 
    public String housecontent(Model model,HttpServletRequest request) throws Exception {	
		String hid = request.getParameter("nid");
		House h = houseService.getHouse(hid);
		Member m = userService.getMemberById(h.getUserId());
		model.addAttribute("user",m);
		if(m.getSex().equals("0")){
			model.addAttribute("Uname",m.getUserName()+"先生");
			
		}else if(m.getSex().equals("1")){
			model.addAttribute("Uname",m.getUserName()+"女士");
		}else model.addAttribute("Uname",m.getUserName()+"小姐");
		model.addAttribute("house",h);
		return "housecontent";
    }
	/**
	 * 房源出售页面
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/house/house-selllist.do") 
    public String houselist(Model model,HttpServletRequest request) throws Exception {	
        //取得查询条件
        Map paramMap = houseService.getParamMap(request);
        List params = (List)paramMap.get("tjs");
        String sql = (String)paramMap.get("sql");
     
        //取得参数
        String _currentPage = request.getParameter("currentPage");
        String _linePerPage = request.getParameter("linePerPage");
        int currentPage = _currentPage == null ? 1 : StringUtils.getStringToInt(_currentPage);
        int linePerPage = _linePerPage == null ? 10 : StringUtils.getStringToInt(_linePerPage);
        //获取查询列表
        List list = tableService.queryForList(sql, params,currentPage,linePerPage);
   
        model.addAttribute("list",list);
        //获取总页数
        int totalNumber = tableService.getTotalNumber(sql,params);
        //放参数
        int totalPage = totalNumber/linePerPage;
        model.addAttribute("totalPage",totalPage+1);
        model.addAttribute("linePerPage",linePerPage);
        model.addAttribute("currentPage",currentPage);
        Map requestParamMap = request.getParameterMap();
        Iterator iterator = requestParamMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = StringUtils.getObjectToString(entry.getKey());
            String value = request.getParameter(key);
            if("keywords".equals(key)){
            	//这边注意，页面url get传参对中文 使用了encodeURI(encodeURI(keywords));所以我们要还原
            	try {
            		value = URLDecoder.decode(value,"utf-8");
        		} catch (UnsupportedEncodingException e) {
        			logger.info("中文参数编码失败！",e);
        		}
            }else if("dateType".equals(key)){
//            	<a class="fcbl " dataType="1" data='2013-06-02' href="#">今日</a>
//    			<a class="fcbl " dataType="2" data='2013-06-02' href="#">本周</a>
//    			<a class="fcbl " dataType="3" data='2013-06-01' href="#">本月</a>
//    			<a class="fcbl " dataType="4" data='2013-01-01' href="#">本年</a>
            	if("1".equals(value)){
            		model.addAttribute("dateTypeZW", "1房");
            	}else if("2".equals(value)){
            		model.addAttribute("dateTypeZW", "2房");
            	}else if("3".equals(value)){
            		model.addAttribute("dateTypeZW", "3房");
            	}else if("4".equals(value)){
            		model.addAttribute("dateTypeZW", "4房");
            	}else if("5".equals(value)){
            		model.addAttribute("dateTypeWZ", "50万以下");
            	}else if("6".equals(value)){
            		model.addAttribute("dateTypeWZ", "51-100万");
            	}else if("7".equals(value)){
            		model.addAttribute("dateTypeWZ", "101万-200万");
            	}else if("8".equals(value)){
            		model.addAttribute("dateTypeWZ", "200万以上");
            	}
            }
            model.addAttribute(key,value);
        }
        
        return "houselist";
    }
	/**
	 * 房源出售页面
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value="/house/house-rentlist.do") 
    public String houserentlist(Model model,HttpServletRequest request) throws Exception {	
        //取得查询条件
        Map paramMap = houseService.getRentParamMap(request);
        List params = (List)paramMap.get("tjs");
        String sql = (String)paramMap.get("sql");
     
        //取得参数
        String _currentPage = request.getParameter("currentPage");
        String _linePerPage = request.getParameter("linePerPage");
        int currentPage = _currentPage == null ? 1 : StringUtils.getStringToInt(_currentPage);
        int linePerPage = _linePerPage == null ? 10 : StringUtils.getStringToInt(_linePerPage);
        //获取查询列表
        List list = tableService.queryForList(sql, params,currentPage,linePerPage);
   
        model.addAttribute("list",list);
        //获取总页数
        int totalNumber = tableService.getTotalNumber(sql,params);
        //放参数
        int totalPage = totalNumber/linePerPage;
        model.addAttribute("totalPage",totalPage+1);
        model.addAttribute("linePerPage",linePerPage);
        model.addAttribute("currentPage",currentPage);
        Map requestParamMap = request.getParameterMap();
        Iterator iterator = requestParamMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = StringUtils.getObjectToString(entry.getKey());
            String value = request.getParameter(key);
            if("keywords".equals(key)){
            	//这边注意，页面url get传参对中文 使用了encodeURI(encodeURI(keywords));所以我们要还原
            	try {
            		value = URLDecoder.decode(value,"utf-8");
        		} catch (UnsupportedEncodingException e) {
        			logger.info("中文参数编码失败！",e);
        		}
            }else if("dateType".equals(key)){
//            	<a class="fcbl " dataType="1" data='2013-06-02' href="#">今日</a>
//    			<a class="fcbl " dataType="2" data='2013-06-02' href="#">本周</a>
//    			<a class="fcbl " dataType="3" data='2013-06-01' href="#">本月</a>
//    			<a class="fcbl " dataType="4" data='2013-01-01' href="#">本年</a>
            	if("1".equals(value)){
            		model.addAttribute("dateTypeZW", "1房");
            	}else if("2".equals(value)){
            		model.addAttribute("dateTypeZW", "2房");
            	}else if("3".equals(value)){
            		model.addAttribute("dateTypeZW", "3房");
            	}else if("4".equals(value)){
            		model.addAttribute("dateTypeZW", "4房");
            	}else if("5".equals(value)){
            		model.addAttribute("dateTypeWZ", "1000以下/月");
            	}else if("6".equals(value)){
            		model.addAttribute("dateTypeWZ", "1000-2000元/月");
            	}else if("7".equals(value)){
            		model.addAttribute("dateTypeWZ", "2000-3000元/月");
            	}else if("8".equals(value)){
            		model.addAttribute("dateTypeWZ", "3000以上/月");
            	}
            }
            model.addAttribute(key,value);
        }
        
        return "house-rentlist";
    }


	
}
